from tcp_service import TCPServer
from utils.logger import logger
import signal
import sys
from config import Config

class ServiceManager:
    def __init__(self):
        self.tcp_server = None
        
    def start(self):
        """启动服务"""
        try:
            logger.info("正在启动 TCP 服务...")
            self.tcp_server = TCPServer()
            self.tcp_server.start()
        except Exception as e:
            logger.error(f"服务启动失败: {str(e)}")
            sys.exit(1)
            
    def stop(self):
        """停止服务"""
        if self.tcp_server:
            logger.info("正在停止 TCP 服务...")
            self.tcp_server.stop()

def signal_handler(signum, frame):
    """处理关闭信号"""
    logger.info("接收到关闭信号，正在关闭服务...")
    if service_manager:
        service_manager.stop()
    sys.exit(0)

service_manager = None

if __name__ == "__main__":
    # 注册信号处理
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # 启动服务
    service_manager = ServiceManager()
    service_manager.start()
    
    # 保持主线程运行
    try:
        # 在 Windows 上使用 while 循环代替 signal.pause()
        while True:
            import time
            time.sleep(1)
    except KeyboardInterrupt:
        logger.info("接收到关闭信号，正在关闭服务...")
        service_manager.stop() 